﻿Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Linq
Imports System.Web.Script.Serialization

''' <summary>
''' Enum for generate log
''' </summary>
''' <remarks></remarks>
Public Enum GenerateScriptLogType
    Insert
    Update
    Delete
End Enum


''' <summary>
''' Provide appropriate hash code for keeping in log
''' </summary>
''' <remarks></remarks>
Public Enum LogMenuType

    LogIn = 1                       '1=เข้าระบบ
    master_department = 2            '2=ระดับหน่วยงาน
    stp_department = 3                  '3=หน่วยงาน
    group_user = 4                  '4=กลุ่มผู้ใช้งาน
    staff = 5                       '5=ผู้ใช้งาน
    master_type = 6                 '6=ประเภทการจัดการข้อมูล
    stp_main_system = 7             '7=ระบบ
    stp_menu_system = 8             '8=เมนูระบบ
    stp_sub_menu = 9                '9=เมนูย่อยระบบ
    stp_auth_department = 10        '10=กำหนดสิทธิ์ใช้งานของหน่วยงาน
    stp_auth_group = 14             '14=กำหนดสิทธิ์ใช้งานของกลุ่มผู้ใช้งาน
    stp_auth_staff = 11             '11=กำหนดสิทธิ์ใช้งานของผู้ใช้งาน
    LogOut = 12                     '12=ออกจากระบบ
    ETC = 13                        '13=อื่นๆ

End Enum



Public Class GenericHelper



    Private Shared _DbStringTypes As System.Data.SqlDbType() = New System.Data.SqlDbType() {System.Data.SqlDbType.NChar, System.Data.SqlDbType.Char, _
                                                           System.Data.SqlDbType.NText, System.Data.SqlDbType.Text, _
                                                           System.Data.SqlDbType.NVarChar, System.Data.SqlDbType.VarChar, _
                                                           System.Data.SqlDbType.DateTime}

    Public Shared Sub ShowAlert(ByVal control As System.Web.UI.TemplateControl, ByVal msg As String)

        ' ============================================
        ' Raise alert message
        ' ============================================
        'msg = msg.Replace(Constants.vbCrLf, "<br />")
        'msg = msg.Replace("'", "''")
        'msg = HttpContext.Current.Server.HtmlEncode(msg)

        Dim js = New JavaScriptSerializer()
        msg = js.Serialize(msg & "")

        ScriptManager.RegisterStartupScript( _
            control, control.GetType(), Guid.NewGuid.ToString(), _
            String.Format(" try{{alert({0});}}catch(ex){{alert(ex)}} ", msg), True)

    End Sub

    Public Shared Sub ShowAlert(ByVal control As System.Web.UI.TemplateControl, ByVal exception As Exception)

        Try
            Dim msg = HttpContext.GetGlobalResourceObject("Resource", exception.Message)
            ShowAlert(control, HttpUtility.HtmlAttributeEncode(msg))
        Catch ex As Exception
            ShowAlert(control, HttpUtility.HtmlAttributeEncode(exception.Message))
        End Try

    End Sub

    Public Shared Sub ShowAlertSuccessful(ByVal control As System.Web.UI.TemplateControl)

        ScriptManager.RegisterStartupScript( _
            control, control.GetType(), Guid.NewGuid.ToString(), _
            String.Format(" try{{alert('ข้อมูลถูกบันทึกเรียบร้อย'); window.open(window.location,'_self');}}catch(ex){{alert(ex)}} "), True)


    End Sub

    ''' <summary>
    ''' Not use 28/11/2553
    ''' </summary>
    ''' <param name="scriptType"></param>
    ''' <param name="cmd"></param>
    ''' <remarks> 
    ''' - This method is not supported complex string format!!!
    ''' - Limited parameter must not more than 20!!!
    ''' </remarks>
    'Public Shared Sub GenerateScript(ByRef scriptType As GenerateScriptLogType, ByVal logType As LogMenuType, ByRef cmd As System.Data.SqlClient.SqlCommand)
    '    ' ============================================
    '    ' Generate log
    '    ' ============================================
    '    Dim str As String = cmd.CommandText
    '    Dim optCode = ""

    '    For Each i As SqlParameter In cmd.Parameters
    '        Dim iReplaced As String = String.Empty
    '        If CheckDbStringType(i.SqlDbType) Then
    '            If i.SqlValue Is Nothing Then
    '                str = str.Replace(i.ParameterName, "NULL")
    '            Else
    '                str = str.Replace(i.ParameterName, "N'" & i.SqlValue.ToString() & "'")
    '            End If
    '        Else
    '            If i.SqlValue Is Nothing Then
    '                str = str.Replace(i.ParameterName, "NULL")
    '            Else
    '                str = str.Replace(i.ParameterName, i.SqlValue.ToString())
    '            End If
    '        End If
    '    Next
    '    Select Case scriptType
    '        Case GenerateScriptLogType.Insert
    '            optCode = "A"
    '        Case GenerateScriptLogType.Update
    '            optCode = "U"
    '        Case GenerateScriptLogType.Delete
    '            optCode = "D"
    '    End Select
    '    cmd.CommandText += Environment.NewLine & _
    '         String.Format("insert into log_system (log_menu,log_type,log_description,staff_ip_address,staff_code_create,create_datetime) values ({0},'" & optCode & "',@GeneratedStatement,'{1}',{2},getdate());", _
    '                       logType.GetHashCode(), HttpContext.Current.Request.UserHostAddress, _
    '                       Profile.ProfileBase.Properties("staff_code").DefaultValue)
    '    If Not String.IsNullOrEmpty(str) Then
    '        cmd.Parameters.AddWithValue("@GeneratedStatement", str)
    '    End If
    'End Sub

    Public Shared Sub GenerateScript(ByRef scriptType As GenerateScriptLogType, ByVal logType As LogMenuType, ByVal newValue As Object, Optional ByVal oldValue As Object = Nothing)

        ' ============================================
        ' Generate log
        ' ============================================
        Dim strLog As String = "ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " "
        Dim optCode As String = ""
        Dim new_value As OrderedDictionary = CType(newValue, OrderedDictionary)
        Dim old_value As OrderedDictionary = Nothing

        Select Case scriptType
            Case GenerateScriptLogType.Insert
                optCode = "A"
                strLog += String.Format("เพิ่มข้อมูลลงตาราง {0} ", logType.ToString())
            Case GenerateScriptLogType.Update
                optCode = "U"
                strLog += String.Format("แก้ไขข้อมูลในตาราง {0} ", logType.ToString())
                If Not oldValue Is Nothing Then old_value = CType(oldValue, OrderedDictionary)
            Case GenerateScriptLogType.Delete
                optCode = "D"
                strLog += String.Format("ลบข้อมูลในตาราง {0} ", logType.ToString())
        End Select

        For i As Int16 = 0 To new_value.Count - 1
            If i < new_value.Count - 1 Then
                If optCode = "U" Then
                    strLog &= String.Format("คอลัมน์: {0} ข้อมูลเดิม: {1}, ", old_value.Keys(i).ToString(), old_value.Values(i).ToString())
                    strLog &= String.Format("ข้อมูลใหม่: {1}, ", new_value.Keys(i).ToString(), new_value.Values(i).ToString())
                Else
                    strLog &= String.Format("คอลัมน์: {0} ข้อมูล: {1}, ", new_value.Keys(i).ToString(), new_value.Values(i).ToString())
                End If
            Else
                If optCode = "U" Then
                    strLog &= String.Format("คอลัมน์: {0} ข้อมูลเดิม: {1}, ", old_value.Keys(i).ToString(), old_value.Values(i).ToString())
                    strLog &= String.Format("ข้อมูลใหม่: {1}", new_value.Keys(i).ToString(), new_value.Values(i).ToString())
                Else
                    strLog &= String.Format("คอลัมน์: {0} ข้อมูล: {1}", new_value.Keys(i).ToString(), new_value.Values(i).ToString())
                End If
            End If
        Next

        CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery( _
        "insert into log_system (log_menu,log_type,log_description,staff_ip_address,staff_code_create,create_datetime) " & _
        "values (@log_menu, @log_type,@log_description, @staff_ip_address, @staff_code_create,getdate());", _
        New SqlParameter("@log_menu", logType.GetHashCode()), _
        New SqlParameter("@log_type", optCode), _
        New SqlParameter("@log_description", strLog), _
        New SqlParameter("@staff_ip_address", HttpContext.Current.Request.UserHostAddress), _
        New SqlParameter("@staff_code_create", HttpContext.Current.Session("staff_code")))

    End Sub

    ''' <summary>
    ''' Private method be used to check paramter is exists db type string whether exists or not.
    ''' </summary>
    ''' <param name="dbType"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function CheckDbStringType(ByVal dbType As System.Data.SqlDbType) As Boolean

        For Each i As System.Data.SqlDbType In _DbStringTypes

            If i = dbType Then

                Return True

            End If

        Next

        Return False

    End Function


    ''' <summary>
    ''' Validate password format!!!
    ''' </summary>
    ''' <param name="password"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function IsAcceptedPassword(ByVal password As String) As Boolean

        Dim isAnyCharacterSet As Boolean = False
        Dim isContainSpecial As Boolean = False

        Dim specialCharacters As String()
        specialCharacters = New String() { _
            "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "{", "}", "[", "]", "\", "/", ".", ",", "+" _
        }

        ' ==============================================================
        ' Compare with set of allowed charters!!!
        ' ==============================================================
        If Regex.Match(password, "!@#$%^&*()_{}[]\/.,+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789").Length > 0 Then
            Return False
        End If

        ' ==============================================================
        ' Is contain at least an special character!!!
        ' ==============================================================
        For Each i As String In specialCharacters
            If password.Contains(i) Then
                isContainSpecial = True
                Exit For
            End If
        Next
        If Not isContainSpecial Then
            Return False
        End If
        If password.Length > 5 And password.Length < 11 Then
            Return True
        Else
            Return False
        End If
    End Function

End Class
